﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.DeepProcess;
using Provenance.Infra.Repositories.DeepProcess;
using Provenance.Write.Api.Application.Command.DeepProcess;

namespace Provenance.Write.Api.Application.CommandHandler.DeepProcess
{
    public class UpRowMaterialCommandHandler : IRequestHandler<UpRowMaterialCommand, ApiResult>
    {
        private readonly IRowMaterialRepository _rowMaterialRepository;
        private readonly ILogger<UpRowMaterialCommandHandler> _logger;
        private readonly IMapper _mapper;
        public UpRowMaterialCommandHandler(IRowMaterialRepository rowMaterialRepository, ILogger<UpRowMaterialCommandHandler> logger, IMapper mapper)
        {
            _rowMaterialRepository = rowMaterialRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(UpRowMaterialCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _rowMaterialRepository.GetAsync(x => x.RowMaterialId == request.RowMaterialId);
                obj = _mapper.Map(request, obj);
                await _rowMaterialRepository.UpdateEntity(obj);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError("Error updating row material: " + ex.Message);
                return ApiResult.Failure(ex.Message);
            }
        }
    }
}
